package com.geccocrawler.gecco.downloader.proxy;

import com.sun.deploy.net.proxy.*;
import org.apache.http.HttpHost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;

public class PacProxys implements Proxys {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private ProxyHandler handler;

    public PacProxys(String url) throws Exception {
        init(url);
    }

    private void init(String url) throws Exception {
        logger.info("the pac url is [{}]", url);
        this.handler = null;
        BrowserProxyInfo b = new BrowserProxyInfo();
        b.setType(ProxyType.AUTO);
        b.setAutoConfigURL(url);
        this.handler = new SunAutoProxyHandler();
        handler.init(b);
        logger.info("init success pac [{}] ", url);
    }

    @Override
    public HttpHost getProxy(String url) {
        try {
            URL u = new URL(url);
            ProxyInfo[] ps = handler.getProxyInfo(u);
            if (ps != null && ps.length > 0) {
                String[] info = ps[0].toString().split(":");
                Proxy proxy = new Proxy(info[0], Integer.parseInt(info[1]));
                return proxy.getHttpHost();
            }
        } catch (Exception e) {
            logger.error("[getProxy] error", e);
        }
        return null;
    }

    @Override
    public boolean addProxy(String host, int port) {
        return false;
    }

    @Override
    public boolean addProxy(String host, int port, String src) {
        return false;
    }

    @Override
    public void failure(String host, int port) {

    }

    @Override
    public void success(String host, int port) {

    }

    public static void main(String[] args) throws Exception {
        BrowserProxyInfo b = new BrowserProxyInfo();
        b.setType(ProxyType.AUTO);
        b.setAutoConfigURL("http://10.10.33.49/pac/proxy.pac");
        SunAutoProxyHandler handler = new SunAutoProxyHandler();
        handler.init(b);
        URL url = new URL("http://www.etnet.com.hk");
        for (int i = 0; i < 100; i++) {
            ProxyInfo[] ps = handler.getProxyInfo(url);
            for (ProxyInfo p : ps)
                System.out.println(p);
        }

    }
}
